<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.12/lib/index.css" />
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    .loadingtext {
      transform: rotate(-90deg);
      color: red;
    }

    .item {
      transform: rotate(-90deg);
    }

    .text {
      text-align: center;
    }

    .boardBox {
      width: 100vw;
      height: 90vh;
      background: #f9f9f9;
    }

    .bar {
      box-sizing: border-box;
      padding: 0rem 1rem;
      display: flex;
      width: 100vw;
      height: 10vh;
      background-color: #ffffff;
      justify-content: space-around;
      align-items: center;
    }

    .shade {
      width: 100vw;
      height: 100vh;
      position: fixed;
      top: 0;
      background-color: #333333;
      z-index: 66666;
      opacity: 0.9;
    }

    .shade .minishade {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .alertpopup {
      padding: 30px 20px;
    }
  </style>
</head>

<body>
  <div id="app">
    <div class="signature" @touchmove.prevent>
      <div class="boardBox" ref="boardBox">
        <canvas ref="board" id="canvas" @touchstart="mStart" @touchmove="mMove" @touchend="mEnd"></canvas>
      </div>
      <div class="bar">
        <div class="item" @click="goback">
          <div class="ico">
            <!-- <img src="@/assets/img/goback.svg" alt srcset /> -->
          </div>
          <div class="text">退出</div>
        </div>
        <div class="item" @click="clearcanvas">
          <div class="ico">
            <!-- <img src="@/assets/img/clear.svg" alt srcset /> -->
          </div>
          <div class="text">重绘</div>
        </div>
        <div class="item" @click="getcanvas">
          <div class="ico">
            <!-- <img src="@/assets/img/qm_sure.svg" alt srcset /> -->
          </div>
          <div class="text">保存</div>
        </div>
      </div>
    </div>

    <van-popup v-model="showPopup" round  close-on-popstate :close-on-click-overlay="false">
      {{ popupTest }}</van-popup>
  </div>
</body>

</html>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vant@2.12/lib/vant.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js"></script>

<script>
  new VConsole();
  const app = new Vue({
    el: '#app',
    data: {
      familysignatureurl: "",
      basedata: "",
      ctx: null,
      point: {
        x: 0,
        y: 0,
      },
      moving: false, // 是否正在绘制中且移动
      hostname: '',
      uuId: '',
      timestamp: '', // 扫码时间戳
      curTimestamp: '', // 当前时间戳
      showPopup: false,
      fiveMinute: 1000 * 60 * 5,
      threeMinute: 1000 * 60 * 3,
      popupTest: null,
      diffTime: "",
      type: "",
      id: "",
      appId: '',
      openId: '',
      orgId: '',
    },
    mounted() {
      this.init()
    },
    watch: {
      diffTime(newVal) {
        if (newVal > this.fiveMinute) {
          clearInterval(this.popupTimer);
          this.popupTimer = null;
          this.popupTest = "二维码已失效，请重新扫码！"
          this.showPopup = true
        }
      }
    },
    methods: {
      init() {
        const { hostname, href } = window.location
        this.hostname = hostname
        const urlParams = new URLSearchParams(href)
        this.timestamp = urlParams.get('timestamp')
        this.type = urlParams.get('type')
        this.id = urlParams.get('id')
        this.uuId = urlParams.get('uuId')
        this.appId = urlParams.get('appId')
        this.openId = urlParams.get('openId')
        this.orgId = urlParams.get('orgId')
        this.createUser = decodeURIComponent(urlParams.get('createUser'))

        const curTimestamp = new Date().getTime() // 当前时间戳
        this.diffTime = curTimestamp - this.timestamp


        if (this.diffTime > this.threeMinute) {
          this.popupTest = "二维码已失效，请重新操作！"
          this.showPopup = true
        } else {
          this.popupTimer = setInterval(() => {
            this.diffTime += 1000;
          }, 1000);
          // 调接口让后台是手机扫码
          this.updateQrStatus();

          let board = this.$refs.board; // 获取DOM
          board.width = this.$refs.boardBox.offsetWidth; // 设置画布宽
          board.height = this.$refs.boardBox.offsetHeight; // 设置画布高
          this.ctx = board.getContext("2d"); // 二维绘图
          this.ctx.strokeStyle = "#000"; // 颜色
          this.ctx.lineWidth = 3; // 线条宽度
        }
      },

      // 触摸(开始)
      mStart(e) {
        let x = e.touches[0].clientX - e.target.offsetLeft,
          y = e.touches[0].clientY - e.target.offsetTop; // 获取触摸点在画板（canvas）的坐标
        this.point.x = x;
        this.point.y = y;
        this.ctx.beginPath();
        this.moving = true;
      },
      // 滑动中...
      mMove(e) {
        if (this.moving) {
          let x = e.touches[0].clientX - e.target.offsetLeft,
            y = e.touches[0].clientY - e.target.offsetTop; // 获取触摸点在画板（canvas）的坐标
          this.ctx.moveTo(this.point.x, this.point.y); // 把路径移动到画布中的指定点，不创建线条(起始点)
          this.ctx.lineTo(x, y); // 添加一个新点，然后创建从该点到画布中最后指定点的线条，不创建线条
          this.ctx.stroke(); // 绘制
          (this.point.x = x), (this.point.y = y); // 重置点坐标为上一个坐标
        }
      },
      // 滑动结束
      mEnd() {
        if (this.moving) {
          this.ctx.closePath(); // 停止绘制
          this.moving = false; // 关闭绘制开关
        }
      },
      getcanvas() {
        //绘画转图片
        document.getElementById("canvas").toDataURL("image/png");
        document.getElementById("canvas").toBlob(async blobObj => {
          let file1 = new File([blobObj], "pic.png", {
            type: blobObj.type,
            lastModified: Date.now(),
          });
          this.convertImg(file1);
        });
      },
      //旋转图片
      convertImg(file) {
        let _this = this;
        let canvas1 = document.createElement("canvas");
        let context1 = canvas1.getContext("2d");
        let oReader = new FileReader();
        oReader.readAsDataURL(file);
        oReader.onload = function (e) {
          let img = new Image();
          img.src = e.target.result;
          img.onload = function () {
            // 图片原始尺寸
            let originWidth = this.width;
            let originHeight = this.height;
            // 最大尺寸限制
            let maxWidth = 1080,
              maxHeight = 1080;
            // 目标尺寸
            let targetWidth = originWidth,
              targetHeight = originHeight;
            // 图片尺寸超过300x300的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                targetWidth = maxWidth;
                targetHeight = Math.round(
                  maxWidth * (originHeight / originWidth)
                );
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(
                  maxHeight * (originWidth / originHeight)
                );
              }
            }
            let type = "image/jpeg";
            // canvas对图片进行缩放
            canvas1.width = targetHeight;
            canvas1.height = targetWidth;
            // 旋转90度
            context1.translate(0, 0);
            context1.rotate(Math.PI / 2);
            // (0,-imgHeight) 从旋转原理图那里获得的起始点
            // context.clearRect(0,  -targetHeight, targetWidth, targetHeight);
            context1.drawImage(img, 0, -targetHeight, targetWidth, targetHeight);
            // 将canvas的透明背景设置成白色
            let imageData = context1.getImageData(
              0,
              0,
              canvas1.width,
              canvas1.height
            );
            for (let i = 0; i < imageData.data.length; i += 4) {
              // 当该像素是透明的，则设置成白色
              if (imageData.data[i + 3] == 0) {
                imageData.data[i] = 255;
                imageData.data[i + 1] = 255;
                imageData.data[i + 2] = 255;
                imageData.data[i + 3] = 255;
              }
            }
            context1.putImageData(imageData, 0, 0);
            let dataurl = canvas1.toDataURL(type);
            _this.basedata = dataurl;
            _this.saveQr(dataurl) // 保存
            _this.updateQrStatus(1) // 修改保存状态
          };
        };
      },
      //base64转Blob
      base64ToBlob(base64Data) {
        let arr = base64Data.split(","),
          fileType = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          l = bstr.length,
          u8Arr = new Uint8Array(l);

        while (l--) {
          u8Arr[l] = bstr.charCodeAt(l);
        }
        return new Blob([u8Arr], {
          type: fileType,
        });
      },
      //上传图片
      async updatavue() {
        //转成file文件
        let blobObj = this.base64ToBlob(this.basedata);
        let file = new File([blobObj], "pic.png", {
          type: blobObj.type,
          lastModified: Date.now(),
        });
        //此处为发送请求给后台获取图片路径
        let res = await upload(file);
        this.familysignatureurl = res.details.data.filePath
      },
      //清除画布
      clearcanvas() {
        let c = document.getElementById("canvas");
        let cxt = c.getContext("2d");
        c.height = c.height;
        this.ctx.lineWidth = 3;
      },
      //更新二维码状态
      async updateQrStatus(operation = 0) {
        const data = {
          uuId: this.uuId,
          operation,
          appId: this.appId,
          createUserId: this.openId,
          orgId: this.orgId,
        }
        await this.axios('/apis/smp/autograph/qrySmpAutographCode', data)
      },
      //新增签名
      async saveQr(base64Code) {
        let data = {
          appId: this.appId,
          createUserId: this.openId,
          orgId: this.orgId,
          createUser: this.createUser,
          base64Code: base64Code.split(',')[1]
        }
        if (this.type === 'edit') data = { ...data, id: this.id };
        const urlSplicing = `${this.type === 'edit' ? 'update' : 'save'}SmpAutograph`

        const { message } = (await this.axios(`/apis/smp/autograph/${urlSplicing}`, data));

        this.popupTest = message
        this.showPopup = true
        setTimeout(() => {
          this.goback();
          this.showPopup = false
        }, 3000)
      },
      // 接口封装
      axios(url, body) {
        return new Promise((resolve, reject) => {
          fetch(url, {
            method: 'POST',
            body: JSON.stringify(body),
            headers: { 'content-type': 'application/json' }
          })
            .then(res => res.json())
            .then(resolve).catch(reject)
        })
      },
      //返回上一级
      goback() {
        //这个可以关闭安卓系统的手机
        document.addEventListener('WeixinJSBridgeReady', function () {
          WeixinJSBridge.call('closeWindow');
        }, false);

        //这个可以关闭ios系统的手机
        WeixinJSBridge.call('closeWindow');
      },
    },
  })
</script>
